<template>
  <div class="hello">
    <el-input placeholder="手机号" v-model="phone" class="button"></el-input>
    <br/>
    <el-input placeholder="密码" v-model="password" class="button"></el-input>
    <br/>
    <el-input placeholder="卡密" v-model="key" class="button"></el-input>
    <br/>
    <el-button type="primary" plain @click="main">确定</el-button>
    <p style="color: #A3A6AD;font-weight: lighter;font-size: smaller;margin-bottom: 0px" >别担心 本项目完全开源且不会保存你的账户信息</p>
    <a style="font-size: small" href="https://gitee.com/TCNotRespond/baijiayun-patcher-web">https://gitee.com/TCNotRespond/baijiayun-patcher-web</a>
    <div class="debug-div"><code class="debug">{{rememberToken}}</code></div>
    <br/>
    <code>{{courseIdList}}</code>
    <br/>
    <code>{{periodId}}</code>
    <br />
    <p style="color: #67C23A">{{done}}</p>
  </div>
</template>

<script>
import axios from "axios";
import qs from 'qs';

export default {
  name: 'HelloWorld',
  props: {
  },
  data() {
    return {
      phone: '',
      password: '',
      key: '',
      rememberToken: '',
      courseIdList:[],
      periodId: [],
      done: ""
    }
  },
  methods: {
    async check() {
      console.log(await this.checkKey("fuck-baijiayun"))
    },

    async main(){
      let check = await this.checkKey(this.key)
      if (!check[0]){
        this.done = check[1]
        return
      }

      await this.getUserToken()
      await this.getCourse(this.rememberToken)

      if (this.rememberToken.length < 2){
        this.done = "账号密码错误"
        return
      }

      for (const courseId of this.courseIdList) {
        const periodId = await this.getPeriodId(this.rememberToken, courseId);
        this.periodId.push({ courseId: courseId, periodId: periodId});
      }
      for (let i in this.periodId){
        let courseId = this.periodId[i].courseId;
        for (let j in this.periodId[i].periodId){
          let periodId = this.periodId[i].periodId[j];
          await this.postPlaybackData(this.rememberToken, courseId, periodId);
          console.log(courseId + "|" + periodId)
        }
      }
      this.done = "已完成 等待半分钟后平台数据更新 刷新平台即可"
    },

    async checkKey(key) {
      try {
          const response = await axios.post(
              'http://baijiayun.sdos.top/key.php',
              qs.stringify({ key: key }), // 使用 qs 库将对象序列化为 URL 编码的字符串
              {
                  headers: {
                      'Content-Type': 'application/x-www-form-urlencoded' // 设置正确的 Content-Type
                  }
              }
          );

          if (response.data.status === "success") {
              return [true,response.data.message];
          } else {
              console.log(response.data.message); // 调试用，输出服务器返回的错误消息
              return [false,response.data.message];
          }
      } catch (error) {
          console.error('Error checking key:', error);
          return false;
      }
    },

    async getUserToken() {
      const requestData = {
        mobile: this.phone,
        password: this.password,
        type: 1,
        client: 1,
        device_id: '',
        prefix_mobile: '086'
      };

      try {
        const response = await axios.post('https://js.szy985.com/api/app/login', requestData);
        if (response.data.code === 200) {
          this.rememberToken = response.data.data.remember_token;
          console.log('Remember Token:', this.rememberToken);
        } else {
          console.error('Login failed:', response.data.msg);
        }
      } catch (error) {
        console.error('Request error:', error);
      }
    },

    async getCourse(rememberToken) {
      const url = 'https://js.szy985.com/api/app/myStudy/1?type=open';

      try {
        const response = await axios.get(url, {
          headers: {
            'Authorization': `Bearer ${rememberToken}`
          }
        });
        if (response.data.code === 200) {
          this.courseIdList = response.data.data.courseList.map(item => item.course_id);
          console.log('courseIdList', this.courseIdList);
        } else {
          console.error('Request failed:', response.data.data.courseList);
        }
      } catch (error) {
        console.error('Request error:', error);
      }
    },

    async getPeriodId(rememberToken,courseId) {
      const url = `https://js.szy985.com/api/app/myStudy/course/${courseId}`;
      try {
        const response = await axios.get(url, {
          headers: {
            'Authorization': `Bearer ${rememberToken}`
          }
        });
        if (response.data.code === 200) {
          let periodId = response.data.data.chapter[0].child.map(item => item.period_id)
          return periodId
        } else {
          console.error('Request failed:', response.data.data.courseList);
        }
      } catch (error) {
        console.error('Request error:', error);
      }
    },
    async postPlaybackData(rememberToken,courseId,periodId) {
      const url = 'https://js.szy985.com/api/app/course/playBack';
      const data = {
        course_basis_id: courseId,
        course_periods_id: periodId,
        total_time: 4800,
        last_time: 4800,
        current_time: 120
      };

      try {
        const response = await axios.post(url, data, {
          headers: {
            'Authorization': `Bearer ${rememberToken}`
          }
        });
        if (response.data.code === 200) {
          console.log('Request successful:', response.data);
        } else {
          console.error('Request failed:', response.data.msg);
        }
      } catch (error) {
        console.error('Request error:', error);
      }
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.debug-div {
  margin-left: 50px;
  margin-right: 50px;
}
.button {
  width: 240px;
  margin-bottom: 10px;
}

.debug {
  word-break: break-all;
  text-align: center;

}
</style>
